from rest_framework import serializers
from .models import Game, GameRound, PlayerAction
from apps.accounts.serializers import UserProfileSerializer
from apps.decks.serializers import DeckSerializer
from apps.cards.serializers import CardSerializer


class GameSerializer(serializers.ModelSerializer):
    """游戏序列化器"""
    player1 = UserProfileSerializer(read_only=True)
    player2 = UserProfileSerializer(read_only=True)
    player1_deck = DeckSerializer(read_only=True)
    player2_deck = DeckSerializer(read_only=True)
    winner = UserProfileSerializer(read_only=True)
    
    class Meta:
        model = Game
        fields = '__all__'


class GameRoundSerializer(serializers.ModelSerializer):
    """游戏回合序列化器"""
    player1_card = CardSerializer(read_only=True)
    player2_card = CardSerializer(read_only=True)
    winner = UserProfileSerializer(read_only=True)
    
    class Meta:
        model = GameRound
        fields = '__all__'


class PlayerActionSerializer(serializers.ModelSerializer):
    """玩家行动序列化器"""
    player = UserProfileSerializer(read_only=True)
    card = CardSerializer(read_only=True)
    
    class Meta:
        model = PlayerAction
        fields = '__all__'


class PlayCardSerializer(serializers.Serializer):
    """出牌序列化器"""
    card_id = serializers.IntegerField()
    
    def validate_card_id(self, value):
        from apps.cards.models import Card
        try:
            card = Card.objects.get(id=value, is_active=True)
        except Card.DoesNotExist:
            raise serializers.ValidationError("卡牌不存在")
        return value
